//
//  ViewController.m
//  贪吃蛇
//
//  Created by xuPeng on 2017/8/14.
//  Copyright © 2017年 陈旭鹏. All rights reserved.
//

#import "ViewController.h"

#define PWidth [UIScreen mainScreen].bounds.size.width
#define PHeight [UIScreen mainScreen].bounds.size.height
#define PCount 30 //地图上可显示的行数。这里规定地图的正方形
#define BoxWidth PHeight/PCount // 每格的宽度

@interface ViewController ()

@property (nonatomic, strong)UIView *mapView;
@property (nonatomic, strong)UIView *food;
@property (nonatomic, assign)NSInteger foodx;
@property (nonatomic, assign)NSInteger foody;
@property (nonatomic, strong)NSMutableArray *body;//蛇的身体是变化的，所以用一个可变数组来存
@property (nonatomic, strong)NSTimer *timer; //定时器
@property (nonatomic, assign)NSInteger directionCode;//定义一个数字来代表方向0，1，2，3分别代表上下左右
@property (nonatomic, assign)float time;//定时器的时间间隔，默认为0.5秒走一步

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatMap];
    [self creatDirectionButton];//创建方向键
    [self creatControlButtons]; //创建开始键、重置键
    [self creatReloadButton];
    
}

- (void)creatMap{
    if (!self.mapView) {
        self.mapView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, PHeight, PHeight)];
        self.mapView.center = self.view.center;
        self.mapView.backgroundColor = [UIColor cyanColor];
        [self.view addSubview:self.mapView];
    }
}

- (void)creatReloadButton{
    UIButton *reloadBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, (PWidth - PHeight)/2, PHeight/3)];
    [reloadBtn setTitle:@"重置/开始" forState:UIControlStateNormal];
    reloadBtn.backgroundColor = [UIColor orangeColor];
    [reloadBtn addTarget:self action:@selector(reloader) forControlEvents:UIControlEventTouchUpInside];
     [self.view addSubview:reloadBtn];
}


- (void)reloader{
    
    self.body = nil;
    for(UIView *subview in self.mapView.subviews){
        if(subview!=self.food){
            [subview removeFromSuperview];
        }
        
    }
    [self creatFood];
    [self createSnake];
    [self createTimer];

}
//创建定时器
-(void)createTimer{
    [self start1];
}
- (void)creatDirectionButton{
    // 左边的方向键view
    UIView *leftDirectionView = [[UIView alloc] initWithFrame:CGRectMake(0, PHeight/3, (PWidth - PHeight)/2, 2*PHeight/3)];
    // 右边的方向键view
    UIView *rightDirectionView = [[UIView alloc] initWithFrame:CGRectMake((PWidth-PHeight)/2+PHeight, PHeight/3, (PWidth - PHeight)/2, 2*PHeight/3)];
    [self.view addSubview:leftDirectionView];
    [self.view addSubview:rightDirectionView];
    
    float btnH = 2*PHeight/9;
    for (int i = 0; i < 4; i++) {
        NSString *title;
        float x;
        float y;
        float w;
        UIColor *backColor;
        switch (i) {
            case 0:
                x=0;
                y=0;
                w = (PWidth - PHeight)/2;
                backColor  = [UIColor redColor];
                title = @"上";
                break;
            case 1:
                x = 0;
                y = btnH;
                w = (PWidth - PHeight)/4;
                backColor = [UIColor grayColor];
                title = @"左";
                break;
            case 2:
                x = (PWidth - PHeight)/4;
                y = btnH;
                w = (PWidth - PHeight)/4;
                backColor = [UIColor orangeColor];
                title = @"右";
                break;
            default:
                x = 0;
                y = 2*btnH;
                w = (PWidth - PHeight)/2;
                backColor = [UIColor greenColor];
                title = @"下";
                break;

        }
        
        UIButton *btnLeft = [[UIButton alloc] initWithFrame:CGRectMake(x,y, w, btnH)];
        btnLeft.tag = i;
        [btnLeft setBackgroundColor:backColor];
        [btnLeft setTitle:title forState:UIControlStateNormal];
        [btnLeft addTarget:self action:@selector(directionChanged:) forControlEvents:UIControlEventTouchUpInside];
        [leftDirectionView addSubview:btnLeft];
        
        UIButton *btnRight = [[UIButton alloc] initWithFrame:CGRectMake(x,y, w, btnH)];
        btnRight.tag = i;
        [btnRight setBackgroundColor:backColor];
        [btnRight setTitle:title forState:UIControlStateNormal];
        [btnRight addTarget:self action:@selector(directionChanged:) forControlEvents:UIControlEventTouchUpInside];
        [rightDirectionView addSubview:btnRight];
    }
    

}
- (void)directionChanged: (UIButton *)sender{
    if (self.directionCode + sender.tag == 3) {
        return;
    }else{
        self.directionCode = sender.tag;

    }
}

- (void)creatControlButtons{
    UIButton *startBtn = [[UIButton alloc] initWithFrame:CGRectMake((PWidth-PHeight)/2+PHeight, 0, (PWidth - PHeight)/4, PHeight/3)];
    [startBtn setTitle:@"继续" forState:UIControlStateNormal];
    startBtn.backgroundColor = [UIColor orangeColor];
    [startBtn addTarget:self action:@selector(start1) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startBtn];
    
    //暂停按钮
    UIButton *stopBtn = [[UIButton alloc]initWithFrame:CGRectMake((PWidth - (PWidth - PHeight)/4), 0, (PWidth - PHeight)/4, PHeight/3 )];
    [stopBtn setTitle:@"暂停" forState:UIControlStateNormal];
    stopBtn.backgroundColor = [UIColor grayColor];
    [stopBtn addTarget:self action:@selector(stop1) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:stopBtn];

}
//初始化定时器的间隔
-(float)time{
    if(!_time){
        _time=0.5;
    }
    return _time;
}

- (void)start1{
    [self.timer invalidate];
    self.timer = [NSTimer timerWithTimeInterval:self.time repeats:YES block:^(NSTimer * _Nonnull timer) {
        [self snakeMove];
    }];
    
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    
}
- (void)stop1{
    [self.timer invalidate];
}
- (void)snakeMove{
    
    //设置蛇身
    for (NSUInteger i = self.body.count - 1; i>0; i--) {
        
        NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithDictionary:self.body[i]];
        NSString *bodyx = self.body[i-1][@"bodyx"];
        NSString *bodyy = self.body[i-1][@"bodyy"];
        [mDic setObject:bodyx forKey:@"bodyx"];
        [mDic setObject:bodyy forKey:@"bodyy"];
        self.body[i] = mDic;
    }
    
    //设置蛇头
    NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithDictionary:self.body[0]];
    NSString *headx = mDic[@"bodyx"];
    NSString *heady = mDic[@"bodyy"];
    if (self.directionCode==0) {
        heady = [NSString stringWithFormat:@"%d",[heady intValue]-1];
    }else if (self.directionCode == 1){
        headx = [NSString stringWithFormat:@"%d",[headx intValue]-1];
    }else if (self.directionCode == 2){
         headx = [NSString stringWithFormat:@"%d",[headx intValue]+1];
    }else if (self.directionCode == 3){
        heady = [NSString stringWithFormat:@"%d",[heady intValue]+1];
    }
    
    [mDic setObject:headx forKey:@"bodyx"];
    [mDic setObject:heady forKey:@"bodyy"];
    self.body[0] = mDic;
    
    //判断是否迟到十五
    if ([headx intValue] == self.foodx && [heady intValue] == self.foody) {
        [self.body addObject:@{@"bodyx":@"-1",@"bodyy":@"0",@"color":[UIColor blueColor]}];
        if (self.time > 0.25) {
            self.time -= 0.05;
            [self start1];
        }
        [self creatFood];
    }
   
    //判断是否撞到边界
    if([headx integerValue]<0||[headx integerValue]>PCount-1||[heady intValue]<0||[heady intValue]>PCount-1){

        [self stop1];
        [self gameOver];
        
        return;
    }
    //判断是否撞到自己
    for (NSUInteger i = 2; i<self.body.count; i++) {
        NSString *bodyx = self.body[i][@"bodyx"];
        NSString *bodyy = self.body[i][@"bodyy"];
        if (headx == bodyx && heady == bodyy) {
            [self stop1];
            [self gameOver];
        }
 
    }
    
    
    [self createSnake];
}
- (void)creatFood{
    //先判断食物是否已经存在，如果存在就不在创建
    if (!self.food) {
        self.food = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BoxWidth, BoxWidth)];
        UIColor *foodColor = [UIColor redColor];
        self.food.backgroundColor = foodColor;
        [self.mapView addSubview:self.food];
    }
    
    //随机位置
    self.foodx = arc4random()%PCount;
    self.foody = arc4random()%PCount;
    self.food.frame = CGRectMake(self.foodx * BoxWidth, self.foody * BoxWidth, BoxWidth, BoxWidth);
    

}

- (void)gameOver{
    UILabel *gameOver = [[UILabel alloc] init];
    gameOver.text = @"GAME OVER!";
    gameOver.textColor = [UIColor redColor];
    [gameOver sizeToFit];
    gameOver.center = CGPointMake(self.mapView.bounds.size.width/2, self.mapView.bounds.size.height/2);
    
    [self.mapView addSubview:gameOver];

}

//创建蛇体
- (void)createSnake{
    if (!_body) {
        self.directionCode = 2;
        self.body = [NSMutableArray arrayWithArray:@[
                                                     @{@"bodyx":@"2",@"bodyy":@"2",@"color":[UIColor redColor]},
                                                     
                                                     @{@"bodyx":@"1",@"bodyy":@"2",@"color":[UIColor blueColor]},
                                                     
                                                     @{@"bodyx":@"0",@"bodyy":@"2",@"color":[UIColor blueColor]},
                                                     ]];
    }

    for (int i = 0; i < self.body.count; i++) {
        NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithDictionary:self.body[i]];
        UIView *body = mDic[@"body"];
        if (!body) {
            body = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BoxWidth, BoxWidth)];
            [self.mapView addSubview:body];
            [mDic setObject:body forKey:@"body"];
            
        }
        
        float bodyx = BoxWidth *[mDic[@"bodyx"] intValue];
        float bodyy = BoxWidth *[mDic[@"bodyy"] intValue];
        body.frame = CGRectMake(bodyx, bodyy, BoxWidth, BoxWidth);
        body.backgroundColor =mDic[@"color"];
        self.body[i] = mDic;
    }

}
@end
